package tpenchere.client.impl;

import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Object;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.Servant;

import tpenchere.client.Client;
import tpenchere.client.ClientHelper;
import tpenchere.service.EnchereService;
import tpenchere.service.EnchereServiceHelper;
import tpenchere.service.EnchereServiceOperations;


public class ClientProvider {
	static String SERVICE_NAME = EnchereService.class.getName();
	static String GLASS = "glassfishorb.properties";
	static String JACORB = "jacorb.properties";
	static String SUN = "sunorb.properties";
	static String IUP = "iuporb.properties";
	
	private static Logger log = Logger.getLogger(ClientProvider.class);
	//initialize 
	public EnchereServiceOperations serviceImpl;
	//servant_to_reference(ClientImpl )
	public Client client;
	protected EnchereClientImpl clientImpl;
	
	public void initClient() {
		String orbPropertyFile = IUP;
		try {
			
			// create and initialize the ORB
			log.info("loading orb.properties: " + orbPropertyFile);

			InputStream is = getClass().getResourceAsStream("/" +
									 orbPropertyFile);
			log.info("input stream: " + is);
			Properties props = new Properties();
			props.load(is);
			
			// create and initialize the ORB
			ORB orb = ORB.init(new String[0], props);

			// get the root naming context
			org.omg.CORBA.Object objRef = orb
					.resolve_initial_references("NameService");
			// Use NamingContextExt instead of NamingContext. This is
			// part of the Interoperable naming Service.
			NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

			// resolve the Object Reference in Naming
			serviceImpl = EnchereServiceHelper.narrow(ncRef.resolve_str(SERVICE_NAME));
			log.info("Obtained a handle on server object");

			//convertir avec le POA manager : servant to reference (impl 2 corba).
			log.info("Convert Client");
			// get reference to rootpoa & activate the POAManager
			POA rootpoa = POAHelper.narrow(orb
					.resolve_initial_references("RootPOA"));
			rootpoa.the_POAManager().activate();
			// get object reference from the servant
			clientImpl = new EnchereClientImpl();
			 Object clientCorba = rootpoa
					.servant_to_reference(clientImpl);
			client = ClientHelper.narrow(clientCorba);
			
		} catch (Exception e) {
			System.out.println("ERROR : " + e);
			e.printStackTrace(System.out);
		} finally {
			if(serviceImpl != null && ! orbPropertyFile.equals(IUP)){
				serviceImpl.shutdown();
			}
		} 
	}
	
	public EnchereServiceOperations getService() {
		return serviceImpl;
	}
	
	public Client getClient() {
		return client;
	}
	
	public EnchereClientImpl getClientImpl() {
		return clientImpl;
	}
}
